package com.thinktank.controller;

import static com.thinktank.util.DbUtil.close;
import static com.thinktank.util.DbUtil.getConnection;

import java.io.IOException;
import java.sql.*;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import com.thinktank.dao.*;
import com.thinktank.vo.*;

public class HomeController implements Controller {
	public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("HomeController");
		// 세션 확인 및 쿠키 로그인
		HttpSession session = request.getSession();
		if(session.getAttribute("member")==null){
			Cookie[] cookies = request.getCookies();
			if (cookies != null) {
				String no = null;
				for (int i = 0; i < cookies.length; i++)
					if (cookies[i].getName().equals("no"))
						no = cookies[i].getValue();
				if ((no != null) && (!no.equals(""))) {
					System.out.println("쿠키로그인");
					Connection con = getConnection();
					MemberDao dao = new MemberDao(con);
					Member member = dao.cookieLogin(no);
					close(con);
					if(member !=null)		session.setAttribute("member", member);
				}
			}
		}
		// 방문 페이지 세션에 저장
		String url=null;
		if(request.getParameter("url")!=null)			url=request.getParameter("url");
		if(url!=null)		session.setAttribute("url", url);
		else{
			Member member = (Member) session.getAttribute("member");
			url = member.getmPage();
			session.setAttribute("url", url);
		}
		

		
		
		// 정보가 있으면 받고 없으면 초기화
		int page = 1;
		String pg = request.getParameter("pg");
		String field = request.getParameter("field");
		String query = request.getParameter("query");
		String icategory="0";
		
		if(pg != null)			page = Integer.parseInt(pg);
		if(field == null)		field = "TITLE";
		if(query == null)		query = "";
		else					query = new String(query.getBytes("ISO-8859-1"), "utf-8");
		

		// 연결 후 DB 작업
		Connection con=getConnection();
		NoticeDao dao = new NoticeDao(con);
		List<Notice> list = dao.getAllNotices(page, field, query, url);
		BoardDao dao2 = new BoardDao(con);
		String field2 = "BD_SUBJECT";
		List<Board> blist = dao2.getAllBoards(page, field2, query, icategory, url);
		close(con);
		
		// 세팅 후 넘기기
		request.setAttribute("list", list);
		request.setAttribute("blist", blist);
		request.setAttribute("query", query);
		
		
		return "home.jsp";
	}
}
